/**
 * 
 */
package controllers;

import javax.swing.JOptionPane;

import client.gui.MainFrame;
import client.gui.panels.Login;
import client.gui.panels.PanelIF;
import entities.Message;

/**
 * LoginController - a controller used for login operation.
 */
public class LoginController implements ControllerIF {
	
	/**
	 * the login panel
	 */
	private Login loginPanel;
	
	/**
	 * the main frame
	 */
	private MainFrame mainFrame;
	
	private boolean flag;
	
	public LoginController(MainFrame mainFrame, Login panel) {
		this.mainFrame = mainFrame;
		this.loginPanel = panel;
		this.loginPanel.setController(this);
	}

	@Override
	public void action() {
		String username = loginPanel.getUsername();
		String password = loginPanel.getPassword();
		
		// username and password tests
		flag = false;
		if(username.isEmpty() || password.isEmpty())
			JOptionPane.showMessageDialog(loginPanel.getParent(), "Please fill all fields before trying to connect...");
		else if( username.length() > 9 || username.length() < 8 || password.length() > 20 || !isNumbers(username) )
			JOptionPane.showMessageDialog(loginPanel.getParent(), "Incorrect username and password. Please try again.", "Error", JOptionPane.ERROR_MESSAGE);
		else {
			mainFrame.loginRequest(username, password);
			flag = true;
		}
	}

	/**
	 * Verify that a string contain numbers only
	 * @param s String to check
	 * @return true if string contains numbers only.
	 * 			false otherwise
	 */
	private boolean isNumbers(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		// only got here if the string didn't return false
		return true;
	}

	@Override
	public PanelIF getPanel() {
		return this.loginPanel;
	}

	@Override
	public void setPanel(PanelIF panel) {
		this.loginPanel = (Login) panel;
	}
	
	/**
	 * Get the user's first name
	 * @return String
	 */
	public String getUserFirstName() {
		return null;
	}

	@Override
	public void decipherMessage(Message message) {
		System.out.println("LoginController.getMessage(): You got here by mistake. Please check your logic...");
	}

	public boolean getFlag() {
		return flag;
	}

}
